import {
	defineStore
} from "pinia";
import {
	ref
} from "vue"
import {
	userLogin,
	getUserInfoApi
} from '@/api/user.js'


// 创建Store
export const useStore = defineStore('userInfo', () => {
	const userInfo = ref({})
	const token = ref('')
	const searchHistory = ref([])
	const getUserInfo = async () => {
		const {
			data
		} = await getUserInfoApi()
		userInfo.value = data

	}

	const addSearchHistory = (value) => {
		searchHistory.value.push(value);
	}
	const login = (code) => {
		var pid = uni.getStorageSync('pid') || '';
		return new Promise((resolve, reject) => {
			userLogin({
				code:code,
				invitor:pid
			}).then((res) => {
				if (res.data) {
					token.value = res.data
					getUserInfo()
					resolve()
				}

			}).catch(() => {
				reject()
			})
		})
	}


	return {
		userInfo,
		getUserInfo,
		addSearchHistory,
		token,
		searchHistory,
		login,
	}
}, {
	// 重要：模块必须开启持久化，才会持久化！！！
	// 注意：默认持久化，只在H5端有效，因为默认使用的是localStorage，小程序端不能使用这个API，所以需要重写存取方法，转调给UniApp的持久化方法
	// persist: true,
	persist: {
		// 默认值，就是使用localStorage
		// storage: localStorage
		// 重写存取方法，转调给UniApp
		storage: {
			getItem(key) {
				return uni.getStorageSync(key)
			},
			setItem(key, val) {
				uni.setStorageSync(key, val)
			}
		}
	}
})